import { Request, Response } from 'express';
import User from '../models/user';
import bcrypt from 'bcryptjs';
import { generateToken } from '../utils/jwt';

// 用户注册控制器
export const registerUser = async (req: Request, res: Response) => {
  try {
    const { username, password, walletAddress } = req.body;
    // 校验必填字段
    if (!username || !password || !walletAddress) {
      return res.status(400).json({ success: false, message: 'All fields are required', data: null });
    }
    // 检查用户名和钱包地址唯一性
    const existingUser = await User.findOne({ username });
    if (existingUser) return res.status(400).json({ success: false, message: 'Username already exists', data: null });
    const existingWallet = await User.findOne({ walletAddress });
    if (existingWallet) return res.status(400).json({ success: false, message: 'Wallet address already registered', data: null });

    // 密码加密存储
    const passwordHash = await bcrypt.hash(password, 10);
    const user = await User.create({ username, passwordHash, walletAddress });

    // 注册成功返回用户信息（不返回token）
    res.status(201).json({
      success: true,
      message: '注册成功',
      data: {
        userId: user._id,
        username: user.username,
        walletAddress: user.walletAddress
      }
    });
  } catch (err) {
    res.status(500).json({ success: false, message: 'Server error', data: null });
  }
};

// 用户登录控制器
export const loginUser = async (req: Request, res: Response) => {
  try {
    const { username, password } = req.body;
    // 校验必填字段
    if (!username || !password) {
      return res.status(400).json({ success: false, message: 'All fields are required', data: null });
    }
    // 查找用户
    const user = await User.findOne({ username });
    if (!user) return res.status(400).json({ success: false, message: 'Invalid username or password', data: null });

    // 校验密码
    const isMatch = await bcrypt.compare(password, user.passwordHash);
    if (!isMatch) return res.status(400).json({ success: false, message: 'Invalid username or password', data: null });

    // 生成JWT token
    const token = generateToken({ userId: user._id });

    // 登录成功返回token和用户信息
    res.json({
      success: true,
      message: '登录成功',
      data: {
        token,
        user: {
          userId: user._id,
          username: user.username,
          walletAddress: user.walletAddress
        }
      }
    });
  } catch (err) {
    res.status(500).json({ success: false, message: 'Server error', data: null });
  }
};

// 获取当前用户信息控制器（需登录）
export const getCurrentUser = async (req: Request, res: Response) => {
  try {
    // 用户ID由认证中间件注入
    const userId = (req as any).user.userId;
    // 查询用户信息，排除密码哈希
    const user = await User.findById(userId).select('-passwordHash');
    if (!user) return res.status(404).json({ success: false, message: 'User not found', data: null });
    res.json({
      success: true,
      data: {
        userId: user._id,
        username: user.username,
        walletAddress: user.walletAddress
      }
    });
  } catch (err) {
    res.status(500).json({ success: false, message: 'Server error', data: null });
  }
};